<template>
  <div class="orgInfo-container">
    <div class="header-title">机构信息</div>
    <el-divider></el-divider>
    <div style="padding-left: 24px">
      <el-form ref="formRef" :rules="rules" :model="form" label-width="80px">
        <el-form-item label="医院名称" prop="orgName">
          <el-input
            v-model="form.orgName"
            placeholder="请输入医院名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="等级选择" prop="level">
          <el-select v-model="form.level" placeholder="请选择等级">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="地区" prop="province">
          <area-cascader
            v-model="form.city"
            v-model:area-all="form.regionName"
            v-model:city="form.city"
            v-model:district="form.district"
            v-model:province="form.province"
          ></area-cascader>
        </el-form-item>
        <el-form-item label="医院地址" prop="regionName">
          <div class="point-select">
            <el-input
              v-model="form.regionName"
              @click="addressClick"
              placeholder="点击选取医院位置"
              :disabled="true"
            ></el-input>
            <el-button type="text" class="ponint-btn" @click="pointsSelClick">
              选取
            </el-button>
          </div>
        </el-form-item>
        <el-form-item label="营业时间" prop="businessHours">
          <div class="business-select">
            <el-time-select
              placeholder="起始时间"
              v-model="form.startTime"
              @change="timeChange"
            ></el-time-select>
            <el-time-select
              placeholder="结束时间"
              v-model="form.endTime"
              :minTime="form.startTime"
              @change="timeChange"
            ></el-time-select>
          </div>
        </el-form-item>
        <el-form-item label="联系电话" prop="mobile">
          <el-input v-model="form.mobile" placeholder="请填写电话"></el-input>
        </el-form-item>
        <el-form-item label="医院介绍" type="textarea" prop="introduction">
          <el-input
            v-model="form.introduction"
            placeholder="请填写医院介绍"
          ></el-input>
        </el-form-item>
        <el-form-item label="医院图片" prop="img">
          <img-upLoad
            v-model="form.img"
            ref="imgUpLoadRef"
            :maxCount="1"
            :isDataWithJSON="false"
            @success="handleAvatarSuccess"
          ></img-upLoad>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">保存</el-button>
          <el-button @click="goBack">返回上一页</el-button>
        </el-form-item>
      </el-form>
    </div>
    <map-point-select
      @ponitChange="ponitChange"
      :visible="isPointSel"
      @close="pointSelClose"
    ></map-point-select>
  </div>
</template>
<script>
  import { reactive, ref } from '@vue/reactivity'
  import { computed, onBeforeMount } from '@vue/runtime-core'
  import { useRouter } from 'vue-router'
  import MapPointSelect from '@/components/MapPointSelect'
  import { orgInfo, save } from '@/api/modules/org'
  import { useRoute } from 'vue-router'
  import { ElMessage } from 'element-plus'
  import areaCascader from '@/components/AreaCascader'
  import imgUpLoad from '@/components/ImgFileUpload'
  import { clone } from 'lodash'
  export default {
    components: { MapPointSelect, areaCascader, imgUpLoad },
    setup() {
      const options = [
        { value: '三甲', label: '三甲' },
        { value: '三乙', label: '三乙' },
        { value: '三丙', label: '三丙' },
        { value: '二甲', label: '二甲' },
        { value: '二乙', label: '二乙' },
        { value: '二丙', label: '二丙' },
        { value: '一甲', label: '一甲' },
        { value: '一乙', label: '一乙' },
        { value: '一丙', label: '一丙' },
      ]

      const formRef = ref(null)
      const isPointSel = ref(false)
      const route = useRoute()

      const form = reactive({
        name: '',
        level: '',
        city: null,
        regionName: '',
        businessHours: '',
        mobile: '',
        introduction: '',
        img: '',
        lat: null,
        lng: null,
        startTime: '',
        endTime: '',
        district: '',
        province: '',
      })

      // 设置请求头
      const header = { ContentType: 'multipart/form-data' }
      const validateImage = (rule, value, callback) => {
        if (value === '' || value === '[]') {
          callback(new Error('请上传图片'))
        }
        callback()
      }
      const rules = {
        orgName: [
          { required: true, message: '请输入医院名称', trigger: 'blur' },
          { min: 0, max: 30, message: '最多30个字符', trigger: 'blur' },
        ],
        level: [
          { required: true, message: '请输入医院等级', trigger: 'change' },
        ],
        province: [
          { required: true, message: '请输入医院所在区域', trigger: 'blur' },
        ],
        regionName: [{ required: true, message: '地图选点', trigger: 'blur' }],
        businessHours: [
          { required: true, message: '营业时间', trigger: 'blur' },
        ],
        mobile: [
          { required: true, message: '请输入电话', trigger: 'blur' },
          { min: 6, message: '至少输入6位以上', trigger: 'blur' },
        ],
        introduction: [
          { required: true, message: '请输入医院介绍', trigger: 'blur' },
          { min: 0, max: 250, message: '最多250个字符', trigger: 'blur' },
        ],
        img: [
          { required: true, message: '请上传图片', trigger: 'blur' },
          { required: true, trigger: 'blur', validator: validateImage },
        ],
      }

      const points = reactive({})
      const ponitChange = function (val) {
        form.regionName = val.poiaddress
        form.lat = val.latlng.lat
        form.lng = val.latlng.lng
        isPointSel.value = false
        console.log('val ' + JSON.stringify(val))
      }

      const pointsSelClick = function () {
        isPointSel.value = true
      }

      const pointSelClose = function () {
        console.log('isPointSel.value = false')
        isPointSel.value = false
      }

      const timeChange = function () {
        if (form.startTime && form.endTime) {
          form.businessHours = form.startTime + '-' + form.endTime
        } else if (!form.startTime || !form.endTime) {
          form.businessHours = null
        }
      }
      const uploadUrl = computed(() => {
        return process.env.VUE_APP_BASE_URL + '/emrweb/file/upload'
      })

      const handleAvatarSuccess = function (val) {
        console.log('上传成功' + JSON.stringify(val))
        form.img = val.data
      }

      const addressClick = function () {
        console.log('addressClick')
      }

      const toSave = async function (form, id) {
        form.name = form.orgName
        await save({ ...form, id })
        goBack()
      }

      const imgUpLoadRef = ref()
      const onSubmit = function () {
        const status = imgUpLoadRef.value.getStatus()
        if (!status) {
          ElMessage.warning('图片还在上传')
          return
        }
        formRef.value.validate((valid) => {
          if (valid) {
            const formc = clone(form)
            // formc.province = formc.province
            // formc.district = formc.district
            const imgObj = formc['img']
            if (imgObj) {
              formc['img'] = JSON.parse(imgObj)[0].url
            }
            toSave(formc, id.value)
            ElMessage.success('提交成功！')
          } else {
            return false
          }
        })
      }

      const router = useRouter()
      const goBack = function () {
        router.go(-1)
      }
      let id = ref(null)
      onBeforeMount(() => {
        if (route.query.id) {
          id.value = route.query.id
          loadData(id.value)
        }
      })
      const loadData = async function (id) {
        const res = await orgInfo({ id })
        if (res.data) {
          Object.keys(res.data).forEach((item) => {
            if (item === 'img') {
              if (res.data[item]) {
                form[item] = JSON.stringify([{ url: res.data[item] }])
              }
            } else {
              form[item] = res.data[item]
            }
          })
          const array = form.businessHours.split('-')
          form.startTime = array[0]
          form.endTime = array[1]
        }
      }
      return {
        form,
        options,
        onSubmit,
        rules,
        uploadUrl,
        header,
        isPointSel,
        goBack,
        handleAvatarSuccess,
        addressClick,
        formRef,
        pointsSelClick,
        pointSelClose,
        points,
        ponitChange,
        timeChange,
        imgUpLoadRef,
      }
    },
  }
</script>
<style lang="scss" scoped>
  .orgInfo-container {
    margin: 32px;
    background-color: white;
    overflow: hidden;

    .point-select {
      .el-input {
        width: 85% !important;
      }
      & .ponint-btn {
        margin-left: 12px;
      }
    }

    .header-title {
      margin-top: 20px;
      margin-left: 11px;
    }
    .el-form {
      width: 50%;

      .el-select {
        width: 100%;
      }

      .el-input {
        width: 100%;
      }
    }
    .business-select {
      & .el-select {
        width: 50%;
      }
    }
    .avatar-uploader :deep(.el-upload) {
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
    }
    .avatar-uploader :deep(.el-upload:hover) {
      border-color: #409eff;
    }
    .avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      line-height: 178px;
      text-align: center;
    }
    .avatar {
      width: 178px;
      height: 178px;
      display: block;
    }
  }
</style>
